import React, { PureComponent, Fragment } from 'react';
import { Map, Marker, Polyline } from 'react-amap';
import { connect } from 'dva';
import { Row, Col, Card, message, Tag, Form, Input, DatePicker, Button, Modal } from 'antd';
import styles from './TravelTrack.less';
import MyInfoWindow from '../../components/GDMap/MyInfoWindow';
import { citys } from '../../utils/city';
import { setCity, getCity } from '../../utils/authority';
import { gcjEncryptta } from '../../utils/gps';
import caron from '../../assets/caron.png';

const { RangePicker } = DatePicker;
const FormItem = Form.Item;

@connect(({ traveltrack, loading }) => ({
  traveltrack,
  loading: loading.effects['traveltrack/fetchmarkerinfo'],
}))
@Form.create()
export default class TravelTrack extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      position: {
        longitude: 121.48,
        latitude: 31.22,
      },

      isClick: false,
      city: '上海市',
      path:
        '[{"longitude":"114.122695","latitude":"22.615686"},{"longitude":"114.120742","latitude":"22.618075"}]',
      passedpath:
        '[{"longitude":"114.122695","latitude":"22.615686"},{"longitude":"114.120742","latitude":"22.618075"}]',
      markhistory: { lng: 121.48, lat: 31.22 },
      visible: true,
      isrealtime: true,
    };

    this.markerEvents = {
      click: e => {
        // 通过高德原生提供的 getExtData 方法获取原始数据
        const marker = e.target;
        const extData = marker.getExtData();
        //console.log('marker pressed', this.state.isClick, extData);
        const tempPosition = { lng: extData.longi, lat: extData.lati };
        this.setState({ position: tempPosition });
        this.setState({ isClick: true });
      },
    };

    this.windowEvents = {
      close: () => {
        this.setState({ isClick: false });
      },
    };
  }

  componentDidMount() {
    const sessionCity = getCity();
    if (sessionCity !== '初始值') {
      // 已有用户选择的城市
      //console.log('session city', sessionCity, citys[sessionCity]);
      this.setState({ city: sessionCity, position: citys[sessionCity] });
    }
    this.startRealTimeMonitor();
    this.forceUpdate();
  }

  componentWillUnmount() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  }

  onLocationError = () => {
    message.info('定位失败.');
    this.props.dispatch({
      type: 'traveltrack/fetchTags',
    });
  };

  getMarker = GeolocationResult => {
    //console.log('GeolocationResult', GeolocationResult);
    const location = GeolocationResult.addressComponent;
    if (location && Object.keys(citys).indexOf(location.city) > -1) {
      // 定位的城市属于 支持城市
      const sessionCity = getCity();
      //console.log('sessionCity', sessionCity);
      if (sessionCity !== '初始值' && sessionCity !== location.city) {
        // 已有选择的城市 且用户选择城市不等于定位城市  优先用户选择
        //console.log('session city', sessionCity, citys[sessionCity]);
        this.setState({ city: sessionCity, position: citys[sessionCity] });
      } else {
        //console.log('find city', location.city, citys[location.city]);
        this.setState({
          city: location.city,
          position: {
            longitude: GeolocationResult.position.lng,
            latitude: GeolocationResult.position.lat,
          },
        });
        //console.log('after set', this.state.city, this.state.position);
        setCity(location.city);
      }
    } else {
      // 定位的城市 系统不支持
      const sessionCity = getCity();
      if (sessionCity !== '初始值') {
        // 已有用户选择的城市

        //console.log('session city', sessionCity, citys[sessionCity]);
        this.setState({ city: sessionCity, position: citys[sessionCity] });
      } else {
        message.info('暂不支持您所在的城市，自动跳转到上海市');
      }
    }
  };

  startRealTimeMonitor = () => {
    const { devId } = this.props.match.params;
    //console.log('devId-------------->', devId);
    const { dispatch } = this.props;
    let temp = {};
    const gdvalue = { longitude: 121.48, latitude: 31.22 };
    dispatch({
      type: 'traveltrack/fetchmarkerinfo',
      payload: { devId },
    });
    this.setState({ deviceId: devId });
    dispatch({
      type: 'traveltrack/getGpsParam',
      payload: { paramName: 'gpsUpdateIntvTime' },
      callback: intervalValue => {
        // if (!this.timer || this.timer === null) {
        this.timer = setInterval(() => {
          this.props.dispatch({
            type: 'traveltrack/fetchmarkerinfo',
            payload: { devId },
            callback: value => {
              // 转换坐标高德坐标
              temp = gcjEncryptta(value.latitude, value.longitude);
              gdvalue.longitude = temp.lng;
              gdvalue.latitude = temp.lat;
              // const tmp=getMovePath();
              const tmp = this.state.path;
              let tempPath = [];
              if (
                tmp ===
                '[{"longitude":"114.122695","latitude":"22.615686"},{"longitude":"114.120742","latitude":"22.618075"}]'
              ) {
                tempPath.push(gdvalue);
              } else {
                tempPath = JSON.parse(tmp);
              }
              const tempPosition = tempPath[tempPath.length - 1];
              if (
                gdvalue.longitude !== tempPosition.longitude &&
                gdvalue.latitude !== tempPosition.latitude
              ) {
                tempPath.push(gdvalue);
              }

              this.setState({ path: JSON.stringify(tempPath) });
              // setMovePath(JSON.stringify(tempPath));
              //console.log('this.state.path：', this.state.path);
              this.forceUpdate();
            },
          });
        }, parseInt(intervalValue, 10) * 1000);
        // }
      },
    });
  };

  handleChange = value => {
    //console.log('city value', value, citys[value]);
    this.setState({ city: value, position: citys[value], isClick: false });
    setCity(value);
    //console.log('getCity', getCity());
    this.props.dispatch({
      type: 'traveltrack/fetchTags',
    });
  };

  startAnimation = () => {
    const statePath = JSON.parse(this.state.path);
    const passedPath = [];
    let k = 0;
    clearInterval(this.timer);
    if (statePath.length !== 0) {
      this.timer = setInterval(() => {
        passedPath.push(statePath[k]);
        const passedmark = { lng: 114.04915418719098, lat: 22.712814085950768 };
        passedmark.lng = statePath[k].longitude;
        passedmark.lat = statePath[k].latitude;

        this.setState({ passedpath: JSON.stringify(passedPath) });
        this.setState({ markhistory: passedmark });
        //console.log('passedmark------>', this.state.markhistory);
        this.forceUpdate();
        if (k < statePath.length - 1) {
          k += 1;
        } else {
          //console.log('轨迹回放结束！');
          clearInterval(this.timer);
        }
      }, 200);
    }
  };

  handleSearch = e => {
    this.setState({
      path:
        '[{"longitude":"114.122695","latitude":"22.615686"},{"longitude":"114.120742","latitude":"22.618075"}]',
    });
    this.setState({
      passedpath:
        '[{"longitude":"114.122695","latitude":"22.615686"},{"longitude":"114.120742","latitude":"22.618075"}]',
    });
    e.preventDefault();
    if (this.state.isrealtime) {
      Modal.info({
        title: '提示',
        content: (
          <div>
            <p>正在实时轨迹监控，请先点击关闭实时轨迹监控！</p>
          </div>
        ),
      });
    } else {
      const { dispatch, form } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        const { devId, date } = fieldsValue;
        let values = {
          devId,
        };
        if (date) {
          const startTime = date[0].format('YYYY-MM-DD HH:mm:ss');
          const endTime = date[1].format('YYYY-MM-DD HH:mm:ss');
          if (startTime.substring(0, 10) !== endTime.substring(0, 10)) {
            Modal.info({
              title: '提示',
              content: (
                <div>
                  <p>开始时间与结束时间必须为同一天！</p>
                </div>
              ),
            });
            return;
          }
          values = {
            ...values,
            startTime,
            endTime,
          };
        }
        dispatch({
          type: 'traveltrack/fetchhistorypath',
          payload: values,
          callback: value => {
            this.setState({ path: value });
            this.forceUpdate();
          },
        });
      });
    }
  };
  trackstate = () => {
    if (this.state.isrealtime) {
      if (this.timer) {
        clearInterval(this.timer);
      }
      this.setState({ isrealtime: false });
      this.setState({
        path:
          '[{"longitude":"114.122695","latitude":"22.615686"},{"longitude":"114.120742","latitude":"22.618075"}]',
      });
    } else {
      clearInterval(this.timer);
      this.startRealTimeMonitor();
      this.setState({ isrealtime: true });
      this.setState({
        path:
          '[{"longitude":"114.122695","latitude":"22.615686"},{"longitude":"114.120742","latitude":"22.618075"}]',
      });
    }
  };

  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    const { devId } = this.props.match.params;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }} type="flex" align="middle">
          <Col md={2} sm={24}>
            历史轨迹：
            <FormItem>
              {getFieldDecorator('devId', {
                rules: [{ required: true, message: '请输入设备ID!' }],
                initialValue: devId === 'init' ? null : devId,
              })(<Input type="hidden" width="1" />)}
            </FormItem>
          </Col>

          <Col md={6} sm={24}>
            <FormItem>
              {getFieldDecorator('date')(
                <RangePicker
                  showTime={{ format: 'HH:mm:ss' }}
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder={['Start Time', 'End Time']}
                  // onChange={onChange}
                  // onOk={onOk}
                  style={{ width: '100%' }}
                />
              )}
            </FormItem>
            <FormItem>
              {getFieldDecorator('mapType', {
                rules: [{ required: true }],
                initialValue: 1,
              })(<Input type="hidden" width="1" />)}
            </FormItem>
          </Col>
          <Col md={2} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" onClick={this.handleSearch}>
                查询
              </Button>
            </span>
          </Col>
          <Col md={2} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" onClick={this.startAnimation}>
                轨迹回放
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderIcon = () => {
    return <img src={caron} className={styles.Appicon} alt="caron" />;
  };
  render() {
    const { traveltrack } = this.props;
    const { devinfo, markPosition } = traveltrack;
    const titlecontent = `设备实时轨迹监控——${devinfo.devName}(${devinfo.devId})`;
    const statePath = JSON.parse(this.state.path);
    const passedPath = JSON.parse(this.state.passedpath);
    const passedMark = this.state.markhistory;

    const extraButton = (
      <div className={styles.extraContent}>
        <Button className={styles.buttonStyle} type="primary" onClick={this.trackstate}>
          {this.state.isrealtime ? '关闭实时监控' : '开启实时监控'}
        </Button>
      </div>
    );
    return (
      <Fragment>
        <Row gutter={24} className={styles.mapRow}>
          <Col xl={24} lg={24} md={24} sm={24} xs={24} className={styles.mapCol}>
            <Card title={titlecontent} bordered={false} extra={extraButton} className={styles.card}>
              <Row>
                <Col md={2} sm={12} xs={24}>
                  实时轨迹监测：
                </Col>
                <Col md={2} sm={12} xs={24}>
                  <Tag color="red">速度:{devinfo.speed}km/h</Tag>
                </Col>
                <Col md={2} sm={12} xs={24}>
                  <Tag color="red">经度:{devinfo.longi}</Tag>
                </Col>
                <Col md={2} sm={12} xs={24}>
                  <Tag color="red">纬度:{devinfo.lati}</Tag>
                </Col>
              </Row>
              <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
              <div
                className={styles.mapChart}
                ref={divElement => {
                  this.divElement = divElement;
                }}
              >
                <Map
                  center={markPosition}
                  zoom="10"
                  amapkey="74532947bf4c342a9f6e1546fe02325f"
                  convert={false}
                >
                  <Marker
                    position={markPosition}
                    extData={devinfo}
                    events={this.markerEvents}
                    render={this.renderIcon}
                  />
                  <Polyline path={statePath} visible={this.state.visible} />
                  <Marker position={passedMark} render={this.renderIcon} />
                  <Polyline
                    path={passedPath}
                    visible={this.state.visible}
                    style={{ strokeColor: '#FF0000' }}
                  />
                  <MyInfoWindow
                    devinfo={devinfo}
                    position={this.state.position}
                    visible={this.state.isClick}
                    events={this.windowEvents}
                    autoMove
                  />
                </Map>
              </div>
            </Card>
          </Col>
        </Row>
      </Fragment>
    );
  }
}
